//
//  LGUserAccountViewModel.swift
//  LGWeibo
//
//  Created by 李更 on 8/12/16.
//  Copyright © 2016 itcast. All rights reserved.
//

import UIKit

class LGUserAccountViewModel: NSObject {
    
    //单例全局访问点
    static let sharedTools : LGUserAccountViewModel = LGUserAccountViewModel()
    
    var userAccount : LGUserAccountModel?
    override init() {
        super.init()
        userAccount = getUserAccount()
    }
    //路径
    let file = (NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last! as NSString).stringByAppendingPathComponent("UserAccount.archive")
    //accesstoken
    var accesstoken : String?{
        if userAccount?.access_token != nil {
            if userAccount?.expires_Date?.compare(NSDate()) == NSComparisonResult.OrderedDescending {
                return userAccount?.access_token
            }else{
                return nil
            }
        }else{
            return nil
        }
    }
    
    var isLogin : Bool {
        return accesstoken != nil
    }
    
  

}

//保存数据
extension LGUserAccountViewModel{
    
    //保存数据
    func saveUserAccount(userAccount : LGUserAccountModel){
        self.userAccount = userAccount
        
       
        
        print(file)
        
        NSKeyedArchiver.archiveRootObject(userAccount, toFile: file)
    }
    //获取数据
    func getUserAccount() ->LGUserAccountModel?{
   
        
        
        let result = NSKeyedUnarchiver.unarchiveObjectWithFile(file) as? LGUserAccountModel
        return result
    }
    
    
    
}


//MARK: -请求数据
extension LGUserAccountViewModel{
    
    //获取授权
    func getUserAccount(code : String , finish :(isSuccess : Bool)->()){
        HMNetworkTools.sharedTools.oauthLoadUserAccount(code, success: { (response) in
            guard let res = response as? [String : AnyObject] else{
                finish(isSuccess: false)
                return
            }
            let userAccount = LGUserAccountModel(dict: res)

            self.getUserInfo(userAccount, finish: finish)
        }) { (error) in
            print("请求失败\(error)")
              finish(isSuccess: false)
        }
    }
    
    func  getUserInfo(userAccount : LGUserAccountModel,  finish :(isSuccess : Bool)->()){
        
        HMNetworkTools.sharedTools.oauthloadUserInfo(userAccount, success: { (response) in
            guard let res = response as? [String : AnyObject] else{
                finish(isSuccess: false)
                return
            }
            //赋值
            userAccount.avatar_large = res["avatar_large"] as? String
            userAccount.screen_name = res["screen_name"] as? String
            print(userAccount)
            self.saveUserAccount(userAccount)
           
            finish(isSuccess: true)
        }) { (error) in
            print("请求失败\(error)")
              finish(isSuccess: false)
        }
    }


}